//use command:[cnpm config get prefix] to see path.
/*
 * NOTE:All js need to debug with alfred.
 */

var utils = require('../AlfredWorkflowUtils.js');
var mysql = require('../AlfredWorkflowMysqlServer.js');
var cons = require('consolidate');

var token = process.argv[2].trim();

var params = ['%'+token+"%"];
var sql = 'select * from alfred_workflow_urls where keyword like ? order by last_check_time desc limit 10';
var tmpl = {isEmpty:false,items:[]};
var item ={uid:"",arg:"",valid:"",title:"",subtitle:""};
var uid = 0;

var itemsRes = mysql.executeSql(sql,params).then(
		function(rows) {
			if(rows&&rows.length>0){
				tmpl.isEmpty = false;
				rows.forEach(function(item, index, array) {
					tmpl.items.push({
						uid : uid++,
						title : item.url,
						subtitle : item.desc,
						arg : item.id+","+item.url,
						valid : true
					});
				});
			}else{
				tmpl.isEmpty = false;
				tmpl.items.push({
					uid : uid++,
					title : "empty",
					subtitle : "empty for params:"+params,
					arg : "",
					valid : false 
				});
			}
		}).then(function(){
			return cons.mustache(__dirname+'/script-input.xml', tmpl);
		}).then(function(res){
			console.log(res);
		}).catch(function(err){
			tmpl.isEmpty = true;
			tmpl.items.push({
				uid : uid++,
				title : "opps,error,check AlfredWorkflowUrl.js",
//				subtitle : 'opps,error,check ~/tools/myGit/xNode/alfred/url/AlfredWorkflowUrl.js',
				subtitle : err,
				arg : "",
				valid : false 
			});
			renderMustache(tmpl);
		});

function renderMustache(source){
	 cons.mustache(__dirname+'/script-input.xml', source)
	 .then(function (res) {
	 console.log(res);
	})};